﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;

namespace Image_Processing
{
    public struct MyColor
    {
      public  byte R, G, B;
        public MyColor(byte r, byte g, byte b)
        {
            R = r;
            G = g;
            B = b;

        }
    } 
    class General_Usage
    {


        public static Bitmap Open_P6Image(string file)
        {
            BinaryReader reader = new BinaryReader(new FileStream(file, FileMode.Open));
            char temp;
            if ((temp=reader.ReadChar()) != 'P' ||( temp=reader.ReadChar()) != '6')
                return null;

            reader.ReadChars(2);//Eat newline // \r\n
           
            string widths = "", heights = "";
            
            while ((temp = reader.ReadChar()) != ' '&&temp>='0'&& temp <= '9')
                widths += temp;
            while ((temp = reader.ReadChar()) >= '0' && temp <= '9')
                heights += temp;

            reader.ReadChar();//line
                  while((temp = reader.ReadChar())=='#')
                  {
                  while((temp = reader.ReadChar())!='\n')
                  {
                  // to read the comments
                  }
                  }
            if ((temp  != '2') || (temp = reader.ReadChar())!= '5' || (temp = reader.ReadChar()) != '5')
                return null;
            reader.ReadChars(2);
           // temp = reader.ReadChar();//Eat the last newline
            int width = int.Parse(widths),
                height = int.Parse(heights);
            Bitmap bitmap = new Bitmap(width, height);
            string[] colors_array;
            //Read in the pixels
            for (int y = 0; y < height; y++)
                for (int x = 0; x < width; x++)
                {

                    string str="";
                        while((temp=reader.ReadChar())!='\n')
                        {
                            if (temp != '\r')
                                str += temp;
                        }
                        colors_array = str.Split(' ');
                    Color color = Color.FromArgb(reader.ReadByte(), reader.ReadByte(), reader.ReadByte());
                    bitmap.SetPixel(x, y,color); 
                }
            return bitmap;
        }
    }
   
    
}
